<template>
  <view>
    <u-popup v-model="showPay" mode="bottom" safe-area-inset-bottom :mask-close-able="false" border-radius="14" closeable @close="handleClose">
      <view class="h-[900rpx]">
        <page-status :status="popupStatus" :fixed="false">
          <template slot="error">
            <u-empty text="订单信息错误，无法查询到订单信息" mode="order"></u-empty>
          </template>
          <template slot="default">
            <view class="payment h-full w-full flex flex-col">
              <view class="header py-[50rpx] flex flex-col items-center">
                <price :content="payData.order_amount" mainSize="44rpx" minorSize="40rpx" fontWeight="500" color="#333"></price>
              </view>
              <view class="main flex-1 mx-[20rpx]">
                <view>
                  <view class="payway-lists">
                    <u-radio-group v-model="payWay" class="w-full">
                      <view class="p-[20rpx] flex items-center w-full payway-item" v-for="(item, index) in payData.lists" :key="index" @click="selectPayWay(item.pay_way)">
                        <u-icon class="flex-none" :size="48" :name="item.icon"></u-icon>
                        <view class="mx-[16rpx] flex-1">
                          <view class="payway-item--name flex-1">{{ item.name }}</view>
                          <view class="text-muted text-xs">{{ item.extra }}</view>
                        </view>

                        <u-radio class="mr-[-20rpx]" :name="item.pay_way"></u-radio>
                      </view>
                    </u-radio-group>
                  </view>
                </view>
              </view>

              <view class="submit-btn p-[20rpx]"><u-button @click="handlePay" shape="circle" type="primary" :loading="isLock">立即支付</u-button></view>
            </view>
          </template>
        </page-status>
      </view>
    </u-popup>

    <u-popup class="pay-popup" v-model="showCheckPay" round mode="center" borderRadius="10" :maskCloseAble="false">
      <view class="content bg-white w-[560rpx] p-[40rpx]">
        <view class="text-2xl font-medium text-center">支付确认</view>
        <view class="pt-[30rpx] pb-[40rpx]"><view>请在微信内完成支付，如果您已支付成功，请点击`已完成支付`按钮</view></view>
        <view class="flex">
          <view class="flex-1 mr-[20rpx]">
            <u-button shape="circle" type="primary" plain size="medium" hover-class="none" :customStyle="{ width: '100%' }" @click="queryPayResult(false)">重新支付</u-button>
          </view>
          <view class="flex-1">
            <u-button shape="circle" type="primary" size="medium" hover-class="none" :customStyle="{ width: '100%' }" @click="queryPayResult()">已完成支付</u-button>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>


<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import { pay } from '@/utils/pay';
// import { getPayWay, prepay, getPayResult } from '@/api/pay'
// import { useLockFn } from '@/hooks/useLockFn'
import { series } from '@/utils/util'
import { ClientEnum, PageStatusEnum, PayStatusEnum, PayWayEnum } from '@/utils/type';
// import { useUserStore } from '@/stores/user'
import { client } from '@/utils/client';
/*
页面参数 orderId：订单id，from：订单来源
*/
export default {
  props: {
    show: {
      type: Boolean,
      required: true
    },
    showCheck: {
      type: Boolean
    },
    // 订单id
    orderId: {
      type: Number,
      required: true
    },
    //订单来源
    from: {
      type: String,
      required: true
    },
    //h5微信支付回跳路径，一般为拉起支付的页面路径
    redirect: {
      type: String
    }
  },
  data() {
    return {
      payWay: '',
      popupStatus: PageStatusEnum.LOADING,
      payData: {
        order_amount: '',
        lists: []
      }
    };
  },
  computed: {
    ...mapState(['userInfo']),
    showCheckPay: {
      get() {
        return this.showCheck;
      },
      set(value) {
        this.$emit('update:showCheck', value);
      }
    },
    showPay: {
      get() {
        console.log('get', this.show)
        return this.show;
      },
      set(value) {
        console.log('set', value)
        this.$emit('update:show', value);
      }
    }
  },
  watch: {
    show: {
      handler(nVal) {
        if (nVal) {
          if (!this.orderId) {
            this.popupStatus = PageStatusEnum.ERROR;
            return;
          }
          this.getPayData();
        }
      },
      immediate: true
    }
  },
  mounted() {
    console.log(this.show);
  },
  methods: {
    handleClose() {
      this.showPay = false;
      this.$emit('close');
    },
    async getPayData() {
      this.popupStatus = PageStatusEnum.LOADING;
      try {
        this.payData = await uni.$u.api.getPayWay({
          order_id: this.orderId,
          from: this.from
        });
        this.popupStatus = PageStatusEnum.NORMAL;
        var checkPay = this.payData.lists.find(item => item.is_default) || this.payData.lists[0];
        this.payWay = checkPay.pay_way;
      } catch (error) {
        this.popupStatus = PageStatusEnum.ERROR;
      }
    },
    selectPayWay(pay) {
      this.payWay = pay;
    },
    async handlePay() {
      try {
        const res = await this.payment();
        this.handlePayResult(res);
        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
        console.log(error);
      }
    },

    handlePayResult(status) {
      switch (status) {
        case PayStatusEnum.SUCCESS:
          this.$emit('success');
          break;
        case PayStatusEnum.FAIL:
          this.$emit('fail');
          break;
      }
    },

    async queryPayResult(confirm = true) {
      const res = await getPayResult({
        order_id: this.orderId,
        from: this.from
      });

      if (res.pay_status === 0) {
        if (confirm == true) {
          uni.$u.toast('您的订单还未支付，请重新支付');
        }
        this.showPay = true;
        this.handlePayResult(PayStatusEnum.FAIL);
      } else {
        if (confirm == false) {
          uni.$u.toast('您的订单已经支付，请勿重新支付');
        }
        this.handlePayResult(PayStatusEnum.SUCCESS);
      }
      this.showCheckPay = false;
    },
    payment() {
      // 查询是否绑定微信
      const checkIsBindWx = async () => {
        if (this.userInfo.is_auth == 0 && [ClientEnum.OA_WEIXIN, ClientEnum.MP_WEIXIN].includes(client) && this.payWay == PayWayEnum.WECHAT) {
          const res = await uni.showModal({
            title: '温馨提示',
            content: '当前账号未绑定微信，无法完成支付',
            confirmText: '去绑定'
          });
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/user_set/user_set'
            });
          }
          return Promise.reject();
        }
      };
      
      // 调用预支付
      const prepayTask = async () => {
        uni.showLoading({
          title: '正在支付中'
        });
        const data = await uni.$u.api.prepay({
          order_id: this.orderId,
          from: this.from,
          pay_way: this.payWay,
          redirect: this.redirect
        });
      
        return data;
      };
      
      //拉起支付
      const payTask = async (data) => {
        try {
          const res = await pay.payment(data.pay_way, data.config);
          return res;
        } catch (error) {
          return Promise.reject(error);
        }
      };
      return series(checkIsBindWx, prepayTask, payTask);
    }
  }
};

// const this.$emit = defineEmits(['update:showCheck', 'update:show', 'close', 'success', 'fail'])

// const userStore = useUserStore();


</script>

<style lang="scss">
.payway-lists {
  .payway-item {
    border-bottom: 1px solid;
    // @apply border-page;
  }
}
</style>
